﻿var _pendingRequests = []; //pendingReqeust: elementId, count

function AddPendingRequest(elementId) {
    var foundRequest = $(_pendingRequests).filter(function () {
        return this.elementId == elementId;
    });

    setTimeout(function () {
        var timedOutRequest = $(_pendingRequests).filter(function () {
            return this.elementId == elementId;
        });
        if (timedOutRequest.length > 0) {
            var message = "A request blocking {0} has either timed out or the PendingRequestFinished method call was not executed against it.".format(elementId);
            if ($status !== undefined) {
                $status.failures = $status.failures == undefined ? [] : $status.failures;
                failure = { "message": message };
                $status.failures.push(failure);
                _ignoreServerStatuses = true;
                ToggleStatuses();
                _ignoreServerStatuses = false;
            } else {

                alert(message);
            }
        }
    }, 5000);

    if (foundRequest.length > 0) {
        foundRequest[0].count++;
    }
    else {

        
        _pendingRequests.push({ "elementId": elementId, "count": 1});
        $(elementId).block(_miniProcessingOptions);
    }
}

function PendingRequestFinished(elementId) {
    var foundRequest = $(_pendingRequests).filter(function () {
        return this.elementId == elementId;
    });

    if (foundRequest.length > 0){
        if(foundRequest[0].count > 1) {
            foundRequest[0].count--;
        }
        else {
            _pendingRequests.splice($.inArray(foundRequest[0], _pendingRequests), 1);
            $(elementId).unblock();
        }
    }
}

